var express = require("express");

var router = express.Router();

var { userModel } = require("../model/model");

const SMSClient = require('@alicloud/sms-sdk')
/* GET home page. */

let strrr = ''
function getCode() {
	let str = "";
	for (let i = 0; i < 6; i++) {
		str += parseInt(Math.random() * 10)
	}
	strrr = str
	return str;
}
router.post('/getyzma', function (req, res, next) {
	let phoneNum = req.body.phone;  //获取前端参数phone
	console.log("手机号码", phoneNum);
	//初始化sms_client
	let smsClient = new SMSClient({
		accessKeyId: 'LTAI5tJANUkrp2DatTmYdAf6',  //accessKeyId 前面提到要准备的
		secretAccessKey: 'Ok0d4QQmMTSBiOHP9D9zed5W0ZUmg7'  //secretAccessKey 前面提到要准备的
	});
	let str = getCode();
	// 开始发送短信
	smsClient.sendSMS({
		PhoneNumbers: phoneNum,
		SignName: "旅游交友", //签名名称 前面提到要准备的
		TemplateCode: "SMS_474880709", //模版CODE  前面提到要准备的
		TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
	}).then(result => {
		console.log("result", result)
		let { Code } = result;
		if (Code == 'OK') {
			res.json({
				code: 0,
				msg: 'success'
			})
			console.log(result)
		}
	}).catch(err => {
		console.log(err);
		res.json({
			code: 1,
			msg: 'fail: ' + err.data.Message
		})
	})
});

router.post("/asdasd", function (req, res, next) {
	res.send({
		code: 0
	})
});
router.post("/getlist", async (req, res, next) => {
	// 此为测试，实际登录需更改


	if ('123456' == req.body.yzm) {
		// if (strrr == req.body.yzm) {
		strrr = ''
		let list = await userModel.find({ phone: req.body.phone })
		if (list.length == 0) {
			await userModel.create({
				username: req.body.phone,
				password: '123456',
				phone: req.body.phone,
				src: 'http://localhost:3000/upload/A3rrQ76kcKfh83Yfp5ppisFC.webp'
			})
			res.send({
				code: 201,
				msg: '注册成功！初始密码为123546'
			})
		} else {
			res.send({
				code: 200,
				msg: '登录成功！',
				name: list[0].username
			})
		}
	} else {
		res.send({
			code: 202,
			msg: '验证码错误！'
		})
	}
});

module.exports = router;